package com.ruoyi.web.controller.module.event;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.event.EventPatrolLine;
import com.ruoyi.system.domain.module.event.EventPatrolLineInfo;
import com.ruoyi.system.domain.module.event.EventPatrolLineInfos;
import com.ruoyi.system.domain.module.event.EventPatrolPoint;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.event.IEventPatrolLineInfoService;
import com.ruoyi.system.service.module.event.IEventPatrolLineService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 巡更线路Controller
 *
 * @author ruoyi
 * @date 2023-12-26
 */
@Validated
@Api(value = "巡更线路控制器", tags = {"巡更线路管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/patrol/line")
public class EventPatrolLineController extends BaseController {

    private final IEventPatrolLineService eventPatrolLineService;
	private final IEventPatrolLineInfoService eventPatrolLineInfoService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
    /**
     * 查询巡更线路列表
     */
    @ApiOperation("查询巡更线路列表")
    @PreAuthorize("@ss.hasPermi('module:patrolLine:list')")
    @GetMapping("/list")
    public TableDataInfo<EventPatrolLine> list(@Validated EventPatrolLine eventPatrolLine) {
		SysUser sysUser = getUser();

		QueryWrapper<EventPatrolLine> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventPatrolLine.getPropertyId() != null){
				qw.eq("property_id",eventPatrolLine.getPropertyId());
			}
			if(eventPatrolLine.getEstateId() != null){
				qw.eq("estate_id",eventPatrolLine.getEstateId());
			}
		}

        TableDataInfo<EventPatrolLine> td = PageUtils.buildDataInfo(eventPatrolLineService.page(PageUtils.buildPage(),qw));
        List<EventPatrolLine> list = td.getRows();
		for (EventPatrolLine list1:list) {
			if (list1.getPropertyId() != null) {
				list1.setPropertyName(propertyService.findById(list1.getPropertyId()).getPropertyName());
			}
			if (list1.getEstateId() != null) {
				list1.setEstateName(estateService.findById(list1.getEstateId()).getEstateName());
			}
		}
        return td;
    }

    /**
     * 导出巡更线路列表
     */
    @ApiOperation("导出巡更线路列表")
    @PreAuthorize("@ss.hasPermi('module:patrolLine:export')")
    @Log(title = "巡更线路", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventPatrolLine> export(@Validated EventPatrolLine eventPatrolLine) {
        List<EventPatrolLine> list = eventPatrolLineService.list();
        ExcelUtil<EventPatrolLine> util = new ExcelUtil<EventPatrolLine>(EventPatrolLine.class);
        return util.exportExcel(list, "巡更线路");
    }

    /**
     * 获取巡更线路详细信息
     */
    @ApiOperation("获取巡更线路详细信息")
    @PreAuthorize("@ss.hasPermi('module:patrolLine:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventPatrolLine> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        EventPatrolLine eventPatrolLine = eventPatrolLineService.getById(id);
		QueryWrapper<EventPatrolLineInfo> qw = new QueryWrapper<>();
		qw.eq("line_id",eventPatrolLine.getId());
		List<EventPatrolLineInfo> list = eventPatrolLineInfoService.list(qw);
		List<EventPatrolLineInfos> list1 = new ArrayList<>();
		for (EventPatrolLineInfo info :list){
			EventPatrolLineInfos infos = new EventPatrolLineInfos();
			infos.setPointId(info.getPointId());
			list1.add(infos);
		}
		eventPatrolLine.setLineInfos(list1);
        return AjaxResult.success(eventPatrolLine);
    }

    /**
     * 新增巡更线路
     */
    @ApiOperation("新增巡更线路")
    @PreAuthorize("@ss.hasPermi('module:patrolLine:add')")
    @Log(title = "巡更线路", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventPatrolLine eventPatrolLine) {
		Boolean br = eventPatrolLineService.save(eventPatrolLine);
		if (eventPatrolLine.getLineInfos()!=null){
			for (int i=0;i<eventPatrolLine.getLineInfos().size();i++){
				EventPatrolLineInfo info1 = new EventPatrolLineInfo();
				info1.setId(null);
				info1.setSort(i);
				info1.setPointId(eventPatrolLine.getLineInfos().get(i).getPointId());
				info1.setLineId(eventPatrolLine.getId());
				br = eventPatrolLineInfoService.save(info1);
			}
		}
        return toAjax(br ? 1 : 0);
    }

    /**
     * 修改巡更线路
     */
    @ApiOperation("修改巡更线路")
    @PreAuthorize("@ss.hasPermi('module:patrolLine:edit')")
    @Log(title = "巡更线路", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventPatrolLine eventPatrolLine) {
		//查询并删除info
		QueryWrapper<EventPatrolLineInfo> qw = new QueryWrapper<>();
		qw.eq("line_id",eventPatrolLine.getId());
		List<EventPatrolLineInfo> list = eventPatrolLineInfoService.list(qw);
		for (EventPatrolLineInfo lineInfo:list){
			eventPatrolLineInfoService.removeById(lineInfo.getId());
		}
		Boolean br = eventPatrolLineService.updateById(eventPatrolLine);
		if (eventPatrolLine.getLineInfos()!=null){
			for (int i=0;i<eventPatrolLine.getLineInfos().size();i++){
				EventPatrolLineInfo info1 = new EventPatrolLineInfo();
				info1.setId(null);
				info1.setSort(i);
				info1.setPointId(eventPatrolLine.getLineInfos().get(i).getPointId());
				info1.setLineId(eventPatrolLine.getId());
				br = eventPatrolLineInfoService.save(info1);
			}
		}
		return toAjax(br ? 1 : 0);
    }

    /**
     * 删除巡更线路
     */
    @ApiOperation("删除巡更线路")
    @PreAuthorize("@ss.hasPermi('module:patrolLine:remove')")
    @Log(title = "巡更线路" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
		for (Integer id:ids){
			QueryWrapper<EventPatrolLineInfo> qw = new QueryWrapper<>();
			qw.eq("line_id",id);
			List<EventPatrolLineInfo> list = eventPatrolLineInfoService.list(qw);
			for (EventPatrolLineInfo lineInfo:list){
				eventPatrolLineInfoService.removeById(lineInfo.getId());
			}
		}
        return toAjax(eventPatrolLineService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
